<script setup>
import {ref, onMounted, onBeforeUnmount, watch} from "vue";
import ace from "ace-builds";
import "ace-builds/src-noconflict/mode-java";
import "ace-builds/src-noconflict/theme-eclipse";
import "ace-builds/src-noconflict/ext-language_tools";

// 接收初始代码内容
const props = defineProps({
  modelValue: String,
});

// 定义事件
const emit = defineEmits(['update:modelValue']);

const editorForm = ref(null);
let editor = null;

// 初始化编辑器
onMounted(() => {
  editor = ace.edit(editorForm.value, {
    theme: `ace/theme/eclipse`,
    mode: `ace/mode/java`,
    maxLines: 20,
    minLines: 10,
    fontSize: 15,
    enableBasicAutocompletion: true,
  });

  // 设置初始值
  editor.setValue(props.modelValue || '', -1);

  // 监听编辑器内容变化 -传递给父组件
  editor.getSession().on('change', () => {
    emit('update:modelValue', editor.getValue());
  });
});

// 监听父组件数据更新
watch(() => props.modelValue, (newCode) => {
  if (editor && newCode !== editor.getValue()) {
    editor.setValue(newCode || '', -1);
  }
});

// 销毁编辑器
onBeforeUnmount(() => {
  if (editor) {
    editor.destroy();
    editor = null;
  }
});

function setEditorCode(content) {
  editor.setValue(content, Infinity)
}

// 将设置代码方法暴露出去
defineExpose({
  setEditorCode
})
</script>

<template>
  <div ref="editorForm" class="ace-editor"></div>
</template>

<style lang="scss" scoped>
.ace-editor {
  margin: 10px 0 0 0;
  width: 100%;
  height: 300px;
}
</style>
